import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    // WEB_ROOT是HTML和其他文件存放的路径（工作路径下/webroot文件夹）
    public static final String WEB_ROOT = System.getProperty("user.dir")
            + File.separator + "webroot";
    // 关闭服务命令
    public static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    public void await() {
        // 创建服务器套接字对象
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            // 这里的ip地址视网络环境进行修改
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("192.168.0.103"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (true) {
            // 创建套接字对象
            Socket socket = null;
            // 创建输入字节流用于获取request请求
            InputStream input = null;
            // 创建输出字节流用于处理response回复
            OutputStream output = null;
            try {
                // 等待连接并获取输入输出流
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();
                // 创建Request对象并解析请求内容
                Request request = new Request(input);
                request.parse();
                // 这里用来处理部分客户端发送空白请求
                if (request.getUri() == null) {
                    continue;
                }
                // 这里检查是否为关闭服务指令
                if (request.getUri().equals(SHUTDOWN_COMMAND)) {
                    break;
                }
                // 创建response对象并赋值
                Response response = new Response(output);
                response.setRequest(request);
                response.sendStaticResource();
                // 关闭socket
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
